package org.jeecg.modules.yw.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.yw.entity.*;
import org.jeecg.modules.yw.result.Result;
import org.jeecg.modules.yw.service.*;
import org.jeecg.modules.yw.utils.CommonUtils;
import org.jeecg.modules.yw.utils.DESUtil;
import org.jeecg.modules.yw.utils.DateUtils;
import org.jeecg.modules.yw.vo.LostsomeapproveVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/app/requestInfo")
@Api(tags = "请假和报工管理")
public class RequestEnterPriseController {
    @Resource
    private RequestEnterPriseService requestService;
    @Resource
    private IRequestapproveService requestapproveService;
    @Resource
    private ILostsomeapproveService lostsomeapproveService;
    @Resource
    private EnterPriseService enterPriseService;
    @Resource
    private MessagesService messagesService;
    @Resource
    private IAttendapproveService attendapproveService;
    @Resource
    private LostSomeService lostSomeService;
    @Resource
    private OrderService orderService;
    @Resource
    private SysAnnoucementService sysAnnoucementService;
    @Autowired
    private IWorkerCompanyRelationService workRelationService;
    @PostMapping("/addRequestEnterPrise")
    @ApiOperation(value = "安装班组或打胶售后 申请工具")
    public Result add(@RequestBody List<RequestEnterPrise> requestEnterPriseList, HttpServletRequest request){

        String t = request.getHeader("token");
        String token = DESUtil.decryptCBCId(t);
        if (token == null){
            return Result.error("未登录");
        }
        EnterPrise enterPrise = enterPriseService.getById(token);
        String enterPriseName = enterPrise.getName();
        if (enterPrise == null){
            return Result.error("用户不存在");
        }
        Messages m = new Messages();
        for (RequestEnterPrise r : requestEnterPriseList){
            if (StringUtils.isBlank(r.getToolNo())&&
                    StringUtils.isBlank(r.getToolType())&&
                    StringUtils.isBlank(r.getUseTime())){
                return Result.error("参数错误");
            }
            DateUtils.strToDate(r.getUseTime());
            r.setId(CommonUtils.getID());
            r.setEnterPriseId(token);
            r.setCreateTime(DateUtils.getCurrentTimeDateStr());
            requestService.save(r);
            Requestapprove approve = new Requestapprove();
            approve.setId(CommonUtils.getID());
            approve.setRequestid(r.getId());
            approve.setCreatetime(DateUtils.getCurrentDate());
            approve.setApprove("0");
            requestapproveService.save(approve);
            String toolName = CommonUtils.getToolName(r.getToolType());
            sysAnnoucementService.AddSysAnnoucement("申请工具消息","姓名:"+enterPriseName+ " 申请工具名称:"+toolName+
                    " 申请数量:"+r.getToolNo(),"15",token,"0","0","0",approve.getId(), enterPrise.getCityCode());
//            m.setId(r.getId());
//            //申请类消息 3
//            m.setMsgType(3);
//            m.setMsgTime(DateUtils.getCurrentTimeDateStr());
//            //state=0 待处理消息
//            m.setState(0);
//            m.setDelFlag(0);
//            //发给中控
//            m.setCurrentUserId("0");
//            messagesService.save(m);
        }
        return Result.success("申请成功");
    }
    //请假
    @ApiOperation(value = "安装班组或打胶售后请假")
    @PostMapping("/leave")
    public Result leave(@RequestBody Attendapprove attendapprove, HttpServletRequest request){
        String s = request.getHeader("token");
        String token = DESUtil.decryptCBCId(s);
        if (token == null){
            return Result.error("未登录");
        }
        try {
            EnterPrise enterPrise = enterPriseService.getById(token);
            attendapprove.setWorkid(token);
            //把保存的逻辑到attendapproveService新方法去处理
            Result result = attendapproveService.addAttendApprove(attendapprove);
            if (result.getCode() != 0){
                return result;
            }
            //发消息
            sysAnnoucementService.AddSysAnnoucement("请假申请",attendapprove.getRemark(),"16",token,"0",
                    "请假无busiId","0",attendapprove.getId(),enterPrise.getCityCode());
//            Messages m = new Messages();
//            m.setId(attendapprove.getId());
//            m.setMsgTime(DateUtils.getCurrentTimeDateStr());
//            m.setMsgType(3);
//            m.setState(0);
//            m.setDelFlag(0);
//            m.setCurrentUserId("0");
//            messagesService.save(m);
            return Result.success("请假申请成功");
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }
    @ApiOperation(value = "安装工人和打胶工人报损")
    @PostMapping("/report")
    public Result report(@RequestBody LostSome lostSome, HttpServletRequest request){
        String s = request.getHeader("token");
        String userId = DESUtil.decryptCBCId(s);
        if (userId == null){
            return Result.error("未登录");
        }
        if (StringUtils.isBlank(lostSome.getGoodName())||StringUtils.isBlank(lostSome.getLostText())||
                StringUtils.isBlank(lostSome.getPicture())){
            return Result.error("参数错误");
        }
        try {
            EnterPrise enterPrise = enterPriseService.getById(userId);
            String OrderId = lostSome.getOrderId();
            Order order = orderService.getById(OrderId);
            if (order == null){
                return Result.error("订单不存在");
            }
            QueryWrapper<LostSome> queryWrapper = new QueryWrapper<LostSome>()
                    .eq("lostStatus", 1)
                    .and(wrapper -> wrapper.eq("orderNo", order.getOrderNo()).or().eq("orderid", order.getId()));
            LostSome one = lostSomeService.getOne(queryWrapper);
            if (one != null){
                return Result.error("该订单已报损");
            }
            lostSome.setOrderId(order.getId());
            lostSome.setOrderNo(order.getOrderNo());
            lostSome.setId(CommonUtils.getID());
            lostSome.setEnterPriseId(userId);
            lostSome.setLostStatus(1);
            lostSomeService.save(lostSome);
            Lostsomeapprove lostsomeapprove = new Lostsomeapprove();
            lostsomeapprove.setId(CommonUtils.getID());
            lostsomeapprove.setLostsomeid(lostSome.getId());
            lostsomeapprove.setApprove("0");
            lostsomeapprove.setCreatetime(DateUtils.getCurrentDate());
            lostsomeapproveService.save(lostsomeapprove);
            String workerIds = workRelationService.getWorkersByCompanyId(order.getCreateUserId());
            sysAnnoucementService.AddSysAnnoucement("报损申请",lostSome.getLostText(),"17",userId,workerIds,
                    order.getId(),"0",lostsomeapprove.getId(), enterPrise.getCityCode());
//            Messages m = new Messages();
//            m.setId(lostSome.getId());
//            m.setOrderId(lostSome.getOrderId());
//            m.setMsgType(3);
//            m.setState(0);
//            m.setDelFlag(0);
//            m.setCurrentUserId("0");
//            messagesService.save(m);
        }catch (Exception e){
            System.err.println(e.getMessage());
            return Result.error("报损申请失败");
        }
        return Result.success(lostSome.getLostStatus());
    }
    @ApiOperation(value="报损审批表-员工查询报损审批")
    @GetMapping(value = "/queryByEnterPriseId")
    public Result queryById(HttpServletRequest request, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                            @RequestParam(name = "orderNo",required = false) String orderNo) {
        String token = request.getHeader("token");
        String id = DESUtil.decryptCBCId(token);//登录人id

        List<LostsomeapproveVo> resultList = lostsomeapproveService.queryList(pageNo, pageSize, id,orderNo);
        return Result.success(resultList);
    }
    @ApiOperation(value="请假审批表-员工请假信息")
    @GetMapping(value = "/queryByEnterIdLeave")
    public Result queryByEnterPriseIdLeave(HttpServletRequest request, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        String token = request.getHeader("token");
        String enterPriseId = DESUtil.decryptCBCId(token);//登录人id
        Page<Attendapprove> page = new Page<>(pageNo, pageSize);
        Result result = attendapproveService.queryByEnterPriseId(page, enterPriseId);
        return result;
    }
}

